package cn.iocoder.yudao.module.enterprise.service.praxisProjectResult;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.enterprise.controller.admin.praxisProject.vo.EnterpriseAnnexVO;
import cn.iocoder.yudao.module.enterprise.controller.admin.praxisProjectResult.vo.EnterpriseProjectResultCreateReqVO;
import cn.iocoder.yudao.module.enterprise.controller.admin.praxisProjectResult.vo.EnterpriseProjectResultPageReqVO;
import cn.iocoder.yudao.module.enterprise.controller.admin.praxisProjectResult.vo.EnterpriseProjectResultRespVO;
import cn.iocoder.yudao.module.enterprise.controller.admin.praxisProjectResult.vo.EnterpriseProjectResultUpdateReqVO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.praxisAnnex.EnterpriseAnnexDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.praxisProject.EnterpriseProjectDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.praxisProjectResult.EnterpriseProjectResultDO;
import cn.iocoder.yudao.module.enterprise.dal.mysql.praxisAnnex.EnterpriseAnnexMapper;
import cn.iocoder.yudao.module.enterprise.dal.mysql.praxisProject.EnterpriseProjectMapper;
import cn.iocoder.yudao.module.enterprise.dal.mysql.praxisProjectResult.EnterpriseProjectResultMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.PRAXIS_PROJECT_RESULT_EXISTS;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.PRAXIS_PROJECT_RESULT_NOT_EXISTS;

/**
 * 项目结果公示 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class EnterpriseProjectResultServiceImpl implements EnterpriseProjectResultService {

    @Resource
    private EnterpriseProjectResultMapper enterpriseProjectResultMapper;
    @Resource
    private EnterpriseProjectMapper enterpriseProjectMapper;
    @Resource
    private EnterpriseAnnexMapper annexMapper;
    @Override
    public Long createPraxisProjectResult(EnterpriseProjectResultCreateReqVO createReqVO) {
        // 插入
        // 插入
        Long aLong = enterpriseProjectResultMapper.selectCount(new QueryWrapper<EnterpriseProjectResultDO>().eq("project_id", createReqVO.getProjectId())
                .eq("deleted", 0) );
        if(null!=aLong && aLong>0){
            throw exception(PRAXIS_PROJECT_RESULT_EXISTS);
        }
        EnterpriseProjectResultDO praxisProjectResult = new EnterpriseProjectResultDO();
        BeanUtils.copyProperties(createReqVO,praxisProjectResult);
        praxisProjectResult.setCreateTime(new Date());
        praxisProjectResult.setUpdateTime(new Date());
        String loginUserName = WebFrameworkUtils.getLoginUserName();
        praxisProjectResult.setCreator(loginUserName);
        praxisProjectResult.setUpdater(loginUserName);
        enterpriseProjectResultMapper.insert(praxisProjectResult);
        List<EnterpriseAnnexVO> annexList = createReqVO.getAnnexList();
        if(CollectionUtils.isNotEmpty(annexList)){
            List<EnterpriseAnnexDO> pList=new ArrayList<>();
            annexList.stream().forEach(m->{
                EnterpriseAnnexDO a=new EnterpriseAnnexDO();
                BeanUtils.copyProperties(m,a);
                a.setId(null);
                a.setRelationId(praxisProjectResult.getId());
                a.setRelationType(2);
                a.setCreateTime(new Date());
                a.setCreator(loginUserName);
                pList.add(a);
            });
            annexMapper.insertBatch(pList);
        }
        return praxisProjectResult.getId();
    }
 
    @Override
    public void updatePraxisProjectResult(EnterpriseProjectResultUpdateReqVO updateReqVO) {
        // 插入
        Long aLong = enterpriseProjectResultMapper.selectCount(new QueryWrapper<EnterpriseProjectResultDO>().eq("project_id", updateReqVO.getProjectId())
                .eq("deleted", 0).ne("id",updateReqVO.getId()));
        if(null!=aLong && aLong>0){
            throw exception(PRAXIS_PROJECT_RESULT_EXISTS);
        }
        // 校验存在
        this.validatePraxisProjectResultExists(updateReqVO.getId());
        // 更新
        EnterpriseProjectResultDO updateObj = new EnterpriseProjectResultDO();
        BeanUtils.copyProperties(updateReqVO,updateObj);
        updateObj.setUpdateTime(new Date());
        updateObj.setUpdater( WebFrameworkUtils.getLoginUserName());
        enterpriseProjectResultMapper.updateById(updateObj);
        List<EnterpriseAnnexVO> annexList = updateReqVO.getAnnexList();
        annexMapper.delete(new QueryWrapper<EnterpriseAnnexDO>().eq("relation_id",updateReqVO.getId()).eq("relation_type",2));
        if(CollectionUtils.isNotEmpty(annexList)){
            List<EnterpriseAnnexDO> pList=new ArrayList<>();
            annexList.stream().forEach(m->{
                EnterpriseAnnexDO a=new EnterpriseAnnexDO();
                BeanUtils.copyProperties(m,a);
                a.setRelationId(updateReqVO.getId());
                a.setId(null);
                a.setCreateTime(new Date());
                a.setRelationType(2);
                a.setCreator( WebFrameworkUtils.getLoginUserName());
                pList.add(a);
            });
            annexMapper.insertBatch(pList);
        }
    }

    @Override
    public void release(@Valid EnterpriseProjectResultUpdateReqVO updateReqVO) {
        enterpriseProjectResultMapper.update(Wrappers.<EnterpriseProjectResultDO>lambdaUpdate()
                .set(EnterpriseProjectResultDO::getUpdateTime,new Date())
                .set(EnterpriseProjectResultDO::getUpdater,WebFrameworkUtils.getLoginUserName())
                .set(EnterpriseProjectResultDO::getStatus,updateReqVO.getStatus())
        .eq(EnterpriseProjectResultDO::getId,updateReqVO.getId()));
    }

    @Override
    public void deletePraxisProjectResult(Long id) {
        // 校验存在
        this.validatePraxisProjectResultExists(id);
        // 删除
        enterpriseProjectResultMapper.deleteById(id);
    }

    private void validatePraxisProjectResultExists(Long id) {
        if (enterpriseProjectResultMapper.selectById(id) == null) {
            throw exception(PRAXIS_PROJECT_RESULT_NOT_EXISTS);
        }
    }

    @Override
    public EnterpriseProjectResultRespVO getPraxisProjectResult(Long id) {
        EnterpriseProjectResultDO p = enterpriseProjectResultMapper.selectById(id);
        if (p == null) {
            throw exception(PRAXIS_PROJECT_RESULT_NOT_EXISTS);
        }
        EnterpriseProjectResultRespVO r = new EnterpriseProjectResultRespVO();
        BeanUtils.copyProperties(p,r);
        QueryWrapper<EnterpriseProjectDO> q=new QueryWrapper<>();
        q.select("title").eq("id",p.getProjectId()).last("limit 1");
        EnterpriseProjectDO projectDO = enterpriseProjectMapper.selectOne(q);
        if(projectDO!=null){
            r.setProjectName(projectDO.getTitle());
        }
        if(null!=r){
            List<EnterpriseAnnexDO> annexDOList = annexMapper.selectList(new QueryWrapper<EnterpriseAnnexDO>().eq("relation_id", id).eq("relation_type", 2));
            if(CollectionUtils.isNotEmpty(annexDOList)){
                List<EnterpriseAnnexVO> pList=new ArrayList<>();
                annexDOList.stream().forEach(m->{
                    EnterpriseAnnexVO a=new EnterpriseAnnexVO();
                    BeanUtils.copyProperties(m,a);
                    pList.add(a);
                });
                r.setAnnexList(pList);
            }
        }
        return r;
    }

    @Override
    public PageResult<EnterpriseProjectResultRespVO> getPraxisProjectResultPage(EnterpriseProjectResultPageReqVO pageReqVO) {
        // MyBatis Plus 查询
        IPage<EnterpriseProjectResultRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getTitle())){
            params.put("title",pageReqVO.getTitle());
        }
        if(StringUtils.isNotBlank(pageReqVO.getCompanyName())){
            params.put("companyName",pageReqVO.getCompanyName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getCreator())){
            params.put("creator",pageReqVO.getCreator());
        }
        if(StringUtils.isNotBlank(pageReqVO.getDept())){
            params.put("dept",pageReqVO.getDept());
        }
        if(null!=pageReqVO.getStatus()){
            params.put("status",pageReqVO.getStatus());
        }
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        params.put("companyId",loginUser.getCompanyId());
        mpPage.setRecords(enterpriseProjectResultMapper.getPraxisProjectResultPage(mpPage, params));
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }


}
